package cn.wolfcode.luowowo.member.service.impl;

import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.common.exception.logicException;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.member.mapper.UserInfoMapper;
import cn.wolfcode.luowowo.member.service.IUserInfoService;
import cn.wolfcode.luowowo.member.util.AssertUtil;
import cn.wolfcode.luowowo.member.util.Consts;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class UserInfoServiceImpl implements IUserInfoService{
    @Autowired
    private UserInfoMapper userInfoMapper;

    @Reference
    private IUserInfoRedisService userInfoRedisService;

    @Override
    public UserInfo get(Long id) {
        return userInfoMapper.selectByPrimaryKey(id);
    }

    @Override
    public boolean checkPhone(String phone) {
        int count = userInfoMapper.selectCountByPhone(phone);
        //如果查出count有数据的话（count =1或以上）就是等于返回true
        return count > 0;
    }

    @Override
    public void sendVerifyCode(String phone) {
        // 生成4位验证码
        String code = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 4);
        // 创建短信并且把验证码放进里面
        StringBuilder sb = new StringBuilder(100);
        sb.append("【螺窝日报】：您的验证码是：").append(code).append(",请在").append(Consts.VERIFY_CODE_VAI_TIME).append("分钟内使用。");
        //发送短信
        System.out.println(sb);
        //将手机，验证码存进redis缓存中
        userInfoRedisService.setVerifyCode(phone,code);
    }

    @Override
    public void userRegist(String phone, String nickname, String password, String rpassword, String verifyCode) throws logicException {
        //判断手机号码格式是否正确（正则表达式）
        Pattern pattern = Pattern.compile("^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(17[013678])|(18[0,5-9]))\\d{8}$");
        pattern.matcher(phone).find();

        //手机号码是否已经注册过
        if (this.checkPhone(phone)){
            throw new logicException("该手机号码已被注册");
        }
        //前台传的参数不能为空
        AssertUtil.hasLength(phone, "手机不能为空");
        AssertUtil.hasLength(nickname, "名称不能为空");
        AssertUtil.hasLength(rpassword, "密码不能为空");
        AssertUtil.hasLength(verifyCode, "验证码不能为空");
        //确认密码要和密码一致
        AssertUtil.isEquals(password, rpassword, "请输入相同的密码");
        //验证码判断
        String code = userInfoRedisService.getVerifyCode(phone);
        if (code == null){
            throw new logicException("验证码已失效");
        }
        if ((!code.equalsIgnoreCase(verifyCode))){
            throw new logicException("验证码错误");
        }
        //注册用户
        UserInfo user = new UserInfo();
        user.setPhone(phone);
        user.setNickname(nickname);
        user.setPassword(password);
        user.setHeadImgUrl("/images/default.jpg");
        user.setLevel(1);
        user.setState(UserInfo.STATE_NORMAL);
        userInfoMapper.insert(user);
    }

    @Override
    public String userLogin(String username, String password) throws logicException{
        //对账号和密码进行校验
        AssertUtil.hasLength(username,"请输入账号");
        AssertUtil.hasLength(password,"请输入密码");

        //对账号密码进行校验
        UserInfo user = userInfoMapper.selectByUsernameandPassword(username, password);
        //对登陆结果进行说明
        if (user.getPhone() == null){
            throw new logicException("帐号不存在");
        }else if (user == null){
            throw new logicException("密码错误");
        }
        //登陆成功之后设置redis的key值和value值
        //redis的key值要唯一所以用一个随机值，value值就是user对象
        String token = UUID.randomUUID().toString().replaceAll("-","");
        //把他们放进token中并且缓存到redis中
        userInfoRedisService.setToken(token, user);
        return token;
    }

    @Override
    public List<UserInfo> list() {
        return userInfoMapper.selectAll();
    }


}
